package com.fliggy.hby_05_02.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fliggy.hby_05_02.common.Result;
import com.fliggy.hby_05_02.common.StaffDataInput;
import com.fliggy.hby_05_02.entity.Business;
import com.fliggy.hby_05_02.entity.IdStaffname;
import com.fliggy.hby_05_02.entity.StaffData;
import com.fliggy.hby_05_02.entity.StaffRelation;
import com.fliggy.hby_05_02.service.BusinessService;
import com.fliggy.hby_05_02.service.IdStaffnameService;
import com.fliggy.hby_05_02.service.StaffDataService;
import com.fliggy.hby_05_02.service.StaffRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/resource")
public class ResourceController {

    @Autowired
    private StaffRelationService staffRelationService;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private IdStaffnameService idStaffnameService;
    @Autowired
    private StaffDataService staffDataService;

    /**
     * 登录，入参为工号staffId，工号存在的话登录成功，否则登录失败
     * @param req
     * @param staffId
     * @return
     */
    @GetMapping("/login")
    public Result<String> login(HttpServletRequest req, String staffId) {
        if (!StringUtils.hasLength(staffId)) {
            return Result.error("工号不能为空");
        }

        LambdaQueryWrapper<StaffRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(staffId != null, StaffRelation::getStaffId, staffId);

        StaffRelation one = staffRelationService.getOne(queryWrapper);
        if (one == null) {
            return Result.error("无权限登录");
        }

        req.getSession().setAttribute("staffId", staffId);

        return Result.success("登录成功");

    }

    /**
     * 查看商业线
     * @return
     */
    @GetMapping("/business_line")
    public Result<List<String>> businessLineQuery() {

        QueryWrapper<Business> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("distinct business_line").lambda();
        List<Business> list = businessService.list(queryWrapper);

        List<String> businessLineList = list.stream().map((item) -> (item.getBusinessLine())).collect(Collectors.toList());
        return Result.success(businessLineList);
    }

    /**
     * 根据商业线查业务线
     * @param businessLine
     * @return
     */
    @GetMapping("/industry_line")
    public Result<List<String>> industryLineQuery(String businessLine) {

        LambdaQueryWrapper<Business> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(businessLine != null, Business::getBusinessLine, businessLine);
        List<Business> businessList = businessService.list(queryWrapper);

        List<String> industryLineList = businessList.stream().map((item) -> (item.getIndustryLine())).collect(Collectors.toList());
        return Result.success(industryLineList);
    }

    /**
     * 根据 当前登录用户信息+几级下属  得到下属列表
     * @param req
     * @param level
     * @return
     */
    @GetMapping("/staff_list")
    public Result<List<String>> staffListQuery(HttpServletRequest req, Integer level) {
        String staffId = (String) req.getSession().getAttribute("staffId");

        LambdaQueryWrapper<StaffRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(staffId != null, StaffRelation::getStaffId, staffId);
        StaffRelation one = staffRelationService.getOne(queryWrapper);

        if (level.equals(1)) {
            String[] subs = one.getSubordinateId().split(",");
            List<String> sub_names = Arrays.stream(subs).map((item) -> {
                LambdaQueryWrapper<IdStaffname> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(item != null, IdStaffname::getStaffId, item);
                IdStaffname oneStaff = idStaffnameService.getOne(queryWrapper1);
                return oneStaff.getStaffName();
            }).collect(Collectors.toList());

            return Result.success(sub_names);
        } else {
            //判断是否有二级下属
            if (one.getSubsubordinateId() == null) {
                return Result.success(null);
            }
            String[] subsubs = one.getSubsubordinateId().split(",");

            List<String> subsub_names = Arrays.stream(subsubs).map((item) -> {
                LambdaQueryWrapper<IdStaffname> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(item != null, IdStaffname::getStaffId, item);
                IdStaffname oneStaff = idStaffnameService.getOne(queryWrapper2);
                return oneStaff.getStaffName();
            }).collect(Collectors.toList());

            return Result.success(subsub_names);
        }

    }

    //当前能修改的年月
    int[] month_calc() {
        int temp_year ,temp_month;
        int temp_day = LocalDate.now().getDayOfMonth();
        int lengthOfMonth = LocalDate.now().lengthOfMonth();
        //填写当月
        if(lengthOfMonth - temp_day <= 3) {
            temp_year = LocalDate.now().getYear();
            temp_month = LocalDate.now().getMonthValue();
        }
        //填写上月
        else {
            temp_year = LocalDate.now().minusMonths(1).getYear();
            temp_month = LocalDate.now().minusMonths(1).getMonthValue();
        }
        return new int[]{temp_year, temp_month};
    }

    /**
     * 资源展示，根据商业线、几级下属、提交年、提交月  列出该月的资源信息
     * @param req
     * @param level
     * @param businessLine
     * @param submitYear
     * @param submitMonth
     * @return
     */
    @GetMapping("/list")
    public Result<Map<String, Map<String, Double>>> resourceListQuery(HttpServletRequest req, Integer level, String businessLine, String submitYear, String submitMonth) {
        //关于月份的计算

        String staffId = (String) req.getSession().getAttribute("staffId");

        LambdaQueryWrapper<StaffRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(staffId != null, StaffRelation::getStaffId, staffId);
        StaffRelation one = staffRelationService.getOne(queryWrapper);

        Map<String, Map<String, Double>> resMap = new HashMap<String, Map<String, Double>>();

        if (level.equals(1)) {
            //得到用户工号和对应花名
            String[] subs = one.getSubordinateId().split(",");
            List<String> sub_names = Arrays.stream(subs).map((item) -> {
                LambdaQueryWrapper<IdStaffname> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(item != null, IdStaffname::getStaffId, item);
                IdStaffname oneStaff = idStaffnameService.getOne(queryWrapper1);
                return oneStaff.getStaffName();
            }).collect(Collectors.toList());
            //去数据库中查找

            for (int i = 0; i < subs.length; i++) {
                String one_id = subs[i];
                String one_name = sub_names.get(i);
                LambdaQueryWrapper<StaffData> queryStaffData1 = new LambdaQueryWrapper<>();
                queryStaffData1.eq(StringUtils.hasLength(one_id), StaffData::getStaffId, one_id);
                queryStaffData1.eq(StringUtils.hasLength(submitYear), StaffData::getSubmitYear, submitYear);
                queryStaffData1.eq(StringUtils.hasLength(submitMonth), StaffData::getSubmitMonth, submitMonth);
                queryStaffData1.eq(StringUtils.hasLength(businessLine), StaffData::getBusinessLine, businessLine);
                List<StaffData> resourceList = staffDataService.list(queryStaffData1);

                Map<String, Double> temp_map = new HashMap<>();
                //生成Map结果，里面存储某个人的多个 行业-资源映射结果
                for (StaffData e : resourceList) {
                    String industry_temp = e.getIndustryLine();
                    Double resource_temp = e.getResource();
                    temp_map.put(industry_temp, resource_temp);
                }
                resMap.put(one_name, temp_map);
            }

        } else {
            //判断是否有二级下属
            if (!StringUtils.hasLength(one.getSubsubordinateId())) {
                return Result.success(null);
            }

            String[] subsubs = one.getSubsubordinateId().split(",");

            List<String> subsubNames = Arrays.stream(subsubs).map((item) -> {
                LambdaQueryWrapper<IdStaffname> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(item != null, IdStaffname::getStaffId, item);
                IdStaffname oneStaff = idStaffnameService.getOne(queryWrapper2);
                return oneStaff.getStaffName();
            }).collect(Collectors.toList());

            //去数据库中查找
            for (int i = 0; i < subsubs.length; i++) {
                String one_id = subsubs[i];
                String one_name = subsubNames.get(i);
                LambdaQueryWrapper<StaffData> queryStaffData1 = new LambdaQueryWrapper<>();
                queryStaffData1.eq(StringUtils.hasLength(one_id), StaffData::getStaffId, one_id);
                queryStaffData1.eq(StringUtils.hasLength(submitYear), StaffData::getSubmitYear, submitYear);
                queryStaffData1.eq(StringUtils.hasLength(submitMonth), StaffData::getSubmitMonth, submitMonth);
                queryStaffData1.eq(StringUtils.hasLength(businessLine), StaffData::getBusinessLine, businessLine);
                List<StaffData> resourceList = staffDataService.list(queryStaffData1);

                Map<String, Double> temp_map = new HashMap<>();
                //生成Map结果，里面存储某个人的多个 行业-资源映射结果
                for (StaffData e : resourceList) {
                    String industry_temp = e.getIndustryLine();
                    Double resource_temp = e.getResource();
                    temp_map.put(industry_temp, resource_temp);
                }
                resMap.put(one_name, temp_map);
            }


        }

        return Result.success(resMap);
    }


    @PostMapping("/save")
    public Result<String> resourceSave(@RequestBody StaffDataInput staffDataInput) {
        String businessLine = staffDataInput.getBusinessLine();
        Map<String, Map<String, Double>> map = staffDataInput.getMap();
        String submitYear = staffDataInput.getSubmitYear();
        String submitMonth = staffDataInput.getSubmitMonth();

        //对月份的判断
        int[] monthCanSubmit = month_calc();
        if (!String.valueOf(monthCanSubmit[0]).equals(submitYear) || !String.valueOf(monthCanSubmit[1]).equals(submitMonth)) {
            return Result.error("提交月份有误，请重试");
        }

        for (Map.Entry<String, Map<String, Double>> entry : map.entrySet()) {
            String name = entry.getKey();
            //根据花名查工号
            LambdaQueryWrapper<IdStaffname> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(name != null, IdStaffname::getStaffName, name);
            IdStaffname one = idStaffnameService.getOne(queryWrapper);
            String staffId = one.getStaffId();

            for (Map.Entry<String, Double> innerEntry : entry.getValue().entrySet()) {
                String industryLine = innerEntry.getKey();
                Double resource= innerEntry.getValue();

                StaffData newStaffData = new StaffData();
                newStaffData.setResource(resource);
                newStaffData.setIndustryLine(industryLine);
                newStaffData.setBusinessLine(businessLine);
                newStaffData.setSubmitYear(submitYear);
                newStaffData.setSubmitMonth(submitMonth);
                newStaffData.setStaffId(staffId);
                newStaffData.setGmtCreate(LocalDateTime.now());
                newStaffData.setGmtModified(LocalDateTime.now());

                staffDataService.save(newStaffData);
            }
        }

        return Result.success("保存成功");
    }
}
